package com.xgp.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@SuppressWarnings("all")
public class C {
    public static void main(String[] args) {

        Data3 data = new Data3();

        new Thread(() -> {for(int i = 0;i < 10;i++) {
            try {
                data.printA();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        },"A").start();
        new Thread(() -> {for(int i = 0;i < 10;i++) {
            try {
                data.printB();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        },"B").start();
        new Thread(() -> {for(int i = 0;i < 10;i++) {
            try {
                data.printC();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        },"C").start();
    }
}


class Data3 {

    private int number = 1;

    private Lock lock = new ReentrantLock();
    //锁监视器(取代了对象监视器的使用)
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void printA() {
        lock.lock();

        try {
            while (number != 1) {
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName());
            //唤醒指定的B
            number = 2;
            condition2.signal();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printB() {
        lock.lock();

        try {
            while (number != 2) {
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName());
            //唤醒指定的B
            number = 3;
            condition3.signal();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC() {
        lock.lock();

        try {
            while (number != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName());
            //唤醒指定的B
            number = 1;
            condition1.signal();
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}